<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2019/1/14
 * Time: 20:18
 */

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;

class Remote extends Controller
{
    /**
     * 初始化
     */
    public function _initialize()
    {
        $username = ssession('username');
        if (empty($username)) {
            $this->redirect('admin/login/login');
        }
        if (!Session::has('user_id')) {
            $this->redirect('admin/login/index');
        }
    }

    /**
     * 列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data = Db::name('remote')
            ->where('user_id', isession('user_id'))
            ->paginate(30);
        $this->assign('list', $data);
        return $this->fetch();
    }

    /**
     * 添加远程数据
     * @return mixed
     */
    public function add()
    {
        if (post()) {
            $data = post();
            $data['user_id'] = isession('user_id');
            $data['username'] = isession('username');
            $data['timestamp'] = time();
            Db::name('remote')->insert($data);
            $this->success('添加成功');
        } else {
            return $this->fetch();
        }
    }

    /**
     * 编辑
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit($id)
    {
        if (post()) {
            $data = post();
            unset($data['id']);
            DB::name('remote')->where('id', post('id'))->update($data);
            $this->success("更新成功");
        } else {
            $info = DB::name('remote')->where('id', $id)->find();
            $this->assign("info", $info);
            return $this->fetch();
        }
    }

    /**
     * 删除
     */
    public function del()
    {
        $data = post();
        if (checkArr($data['id'])) {
            $where = "id in (" . join(",", $data['id']) . ")";
        } else {
            $where = "id =" . $data['id'];
        }
        Db::name('remote')->where($where)->delete();
        $this->success("删除成功");
    }
}